import React, { useState } from "react";
import {
    DesktopOutlined,
    FileOutlined,
    PieChartOutlined,
    TeamOutlined,
    UserOutlined,
} from "@ant-design/icons";
import type { MenuProps } from "antd";
import { Menu } from "antd";
import { useLocation, useNavigate } from "react-router-dom";

type MenuItem = Required<MenuProps>["items"][number];

const items: MenuItem[] = [
    {
        label: "栏目 1",
        key: "/page1",
        icon: <PieChartOutlined />,
    },
    {
        label: "栏目 2",
        key: "/page2",
        icon: <DesktopOutlined />,
    },
    {
        label: "栏目 3",
        key: "page3",
        icon: <UserOutlined />,
        children: [
            { label: "栏目 301", key: "/page3/page301" },
            { label: "栏目 302", key: "/page3/page302" },
            { label: "栏目 303", key: "/page3/page303" },
        ],
    },
    {
        label: "栏目 4",
        key: "page4",
        icon: <TeamOutlined />,
        children: [
            { label: "栏目 401", key: "/page4/page401" },
            { label: "栏目 402", key: "/page4/page402" },
        ],
    },
    {
        label: "栏目 5",
        key: "/page5",
        icon: <FileOutlined />,
    },
];

const MinMenu: React.FC = () => {
    const navigateTo = useNavigate();
    const currentRoute = useLocation();
    
    // 处理菜单点击事件
    const menuClick = (e: { key: string }) => {
        navigateTo(e.key);
    };

    // 处理菜单展开的 key
    const handleCollapse = (keys: string[]) => {
        setOpenKeys(keys.length > 0 ? [keys[keys.length - 1]] : []);
    };

    // 递归查找当前选中的 key 是否在某个 children 内部
    const findOpenKey = (menuItems: MenuItem[], path: string): string | undefined => {
        for (const item of menuItems) {
            if (!item || typeof item !== "object" || !("children" in item)) continue; // 处理 item 可能为 null 的情况
            if (item.children) {
                if (item.children.some((child) => child && child.key === path)) {
                    return item.key as string;
                }
                const found = findOpenKey(item.children, path);
                if (found) return found;
            }
        }
        return undefined;
    };

    // 计算默认展开的 key
    const firstOpenKey = findOpenKey(items, currentRoute.pathname) || "";

    const [openKeys, setOpenKeys] = useState<string[]>(firstOpenKey ? [firstOpenKey] : []);

    return (
        <Menu
            theme="dark"
            defaultSelectedKeys={[currentRoute.pathname]}
            mode="inline"
            items={items}
            onClick={menuClick}
            onOpenChange={handleCollapse}
            openKeys={openKeys}
        />
    );
};

export default MinMenu;
